import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { AddAreaListFormValuesType, patrolsUpdateStateType } from './typings'
import { defineComponent, reactive, ref } from 'vue'
import {
  ElDialog,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElLink,
  ElButton,
  ElMessage
} from 'element-plus'
import { cloneDeep } from 'lodash'
import { handleTrim } from '~/utils/util'
import ProSaasTable from '~/components/ProSaasTable'
import SearchForm from '~/components/ProForm/SearchForm'
import MapView from '../map/MapView' // 地图
import useVuexGetters from '~/hooks/useVuexGetters'
import styles from '~/pages/oam/index.module.scss'

export default defineComponent({
  name: 'AddAreaList',
  props: {
    showAddAreaList: {
      type: Boolean,
      default: false
    }
  },
  emits: ['handleClose', 'selectedArea'],
  setup(props, { emit }) {
    // 初始化
    const proSaasTableRef = ref<ProSaasTableExposeType>()
    const mapViewRef = ref() // 地图
    const formValues = reactive<AddAreaListFormValuesType>({}) // 搜索内容

    const orderState = useVuexGetters('order', ['appointmentTimeEnum'])

    // 其他值
    const state = reactive<patrolsUpdateStateType>({
      showAddAreaMap: false // 地图定位 弹窗是否显示
    }) // 地图的点 markers

    // methods
    // 点击台区列表的操作列(地图), 在地图显示该台区地址
    const lookPointOnMap = (row: AddAreaListFormValuesType) => {
      try {
        state.showAddAreaMap = true
        state.markers = { lng: row.longitude!, lat: row.latitude! }
        setTimeout(() => {
          mapViewRef.value.setMarkersByPropsMarkers()
        }, 100)
      } catch (error) {
        ElMessage({
          message: '暂无当前地点坐标噢',
          type: 'warning'
        })
      }
    }

    // 回传选中的台区们
    const submit = () => {
      const element = cloneDeep(proSaasTableRef.value?.selecteds)
      if (element.length === 0) {
        ElMessage({
          message: '请选择台区',
          type: 'warning'
        })
        return
      }

      if (element.length !== 0) {
        proSaasTableRef.value!.elTableRef.clearSelection()
        emit('selectedArea', element)
        emit('handleClose')
      }
    }

    // 表格字段
    const columns: TableColumnProps<AddAreaListFormValuesType>[] = [
      {
        label: '台区名称',
        prop: 'coursName',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '所属工区',
        prop: 'coursArea',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '台区地址',
        prop: 'coursAddress',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '是否加入巡视计划',
        prop: 'isPlan',
        minWidth: 180,
        enumValues: orderState.appointmentTimeEnum,
        align: 'center'
      },
      {
        label: '所属巡视分组',
        prop: 'patrolPlanName',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '操作',
        prop: 'options',
        minWidth: 90,
        // width: 70,
        align: 'center',
        render: ({ row }) => (
          <ElLink type="warning" onClick={() => lookPointOnMap(row)}>
            地图
          </ElLink>
        )
      }
    ]

    return () => (
      <>
        <ElDialog
          modelValue={props.showAddAreaList}
          width="65%"
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={() => {
            emit('handleClose')
          }}
          title="选择台区"
          append-to-body
        >
          <SearchForm
            searchFormProps={{
              model: formValues
            }}
            searchformResponsiveCol={[
              <ElFormItem key="name" prop="name" label="台区搜索：">
                <ElInput v-model={formValues.name} placeholder="请输入台区名称" clearable />
              </ElFormItem>,
              <ElFormItem key="isPlan" prop="isPlan" label="是否加入巡视计划：">
                <ElSelect v-model={formValues.isPlan} placeholder="请选择" clearable>
                  <ElOption key={1} label="是" value={1} />
                  <ElOption key={0} label="否" value={0} />
                </ElSelect>
              </ElFormItem>
            ]}
            handleSearchList={proSaasTableRef.value?.toSearch}
          />
          <ProSaasTable<AddAreaListFormValuesType>
            ref={proSaasTableRef}
            columns={columns}
            searchParams={{
              name: formValues.name && handleTrim(formValues.name)
            }}
            searchFormProps={{
              model: formValues
            }}
            hasSelection
            dispatchType="patrol/PostAddAreaListSelect"
          />
          <div class={styles['patrol-submitAndCancel-btn']}>
            <ElButton type="primary" size="default" onClick={() => submit()}>
              确 定
            </ElButton>
            <ElButton
              size="default"
              onClick={() => {
                emit('handleClose')
              }}
            >
              取 消
            </ElButton>
          </div>
        </ElDialog>

        <ElDialog // 新增台区->列表操作列(地图)->地图定位
          modelValue={state.showAddAreaMap!}
          width="50%"
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={() => {
            state.showAddAreaMap = false
          }}
          title="地图的定位"
          append-to-body
        >
          <div class={styles['patrolUpdate-map']}>
            <MapView
              id="addAreaListMap"
              ref={mapViewRef}
              markers={state.markers}
              needMultipleMarker={false} // 单点标记
              orderMarker={false} // 不为工单地图
            />
          </div>
        </ElDialog>
      </>
    )
  }
})
